package cn.sanch.user.service.impl;

import cn.sanch.basic.constant.VerifyConstants;
import cn.sanch.user.dto.UserDto;
import cn.sanch.basic.util.BusinessException;
import cn.sanch.basic.util.MD5Utils;
import cn.sanch.basic.util.StrUtils;
import cn.sanch.user.domain.Logininfo;
import cn.sanch.user.domain.User;
import cn.sanch.user.dto.UserEmailDto;
import cn.sanch.user.mapper.LogininfoMapper;
import cn.sanch.user.mapper.UserMapper;
import cn.sanch.user.service.IUserService;
import cn.sanch.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 手机号码注册
     * @param userDto
     */
    @Override
    public void phoneRegister(UserDto userDto) {
        //1.空值校验
        if (
                userDto.getPhone().isEmpty()
                || userDto.getPhoneCode().isEmpty()
                || userDto.getPassword().isEmpty()
                || userDto.getPasswordRepeat().isEmpty()
        ) {
           throw new BusinessException("请填写完整信息！");
        }

        //2.邮箱格式是否正确
        

        //2.校验两次密码是否相等
        if (!userDto.getPassword().trim().equals(userDto.getPasswordRepeat().trim())) {
            throw new BusinessException("两次密码输入不相同，请重新输入！");
        }

        //3.校验短信验证码是否过期
        //通过key【register:手机号】获取redis储存的短信验证码【短信验证码:时间戳】
        Object redisPhoneCode = redisTemplate.opsForValue().get(VerifyConstants.REGISTER_PREFIX + userDto.getPhone());
        if (redisPhoneCode == null) {
            throw new BusinessException("验证码已过期，请重新获取！");
        }

        //4.校验短信验证码是否相等
        String phoneCode = redisPhoneCode.toString().split(":")[0];
        if (!userDto.getPhoneCode().equalsIgnoreCase(phoneCode)) {
            throw new BusinessException("验证码输入错误！");
        }

        //5.保存logininof数据
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        //先保存logininof数据才能拿到Logininfo_id保存到user表中
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());

        //6.保存user数据
        userMapper.save(user);
    }


    /**
     * 邮箱注册
     * @param userEmailDto
     */
    @Override
    public void emailRegister(UserEmailDto userEmailDto) {
        //1.空值校验
        if (
              userEmailDto.getEmail().isEmpty()
              || userEmailDto.getPassword().isEmpty()
              || userEmailDto.getPasswordRepeat().isEmpty()
        ) {
            throw new BusinessException("请填写完整信息！");
        }
        //2.校验两次密码是否相等
        if (!userEmailDto.getPassword().trim().equals(userEmailDto.getPasswordRepeat().trim())) {
            throw new BusinessException("两次密码输入不相同，请重新输入！");
        }

        //3.校验图形验证码是否过期
        //获取redis中的验证码
        Object redisImageCode = redisTemplate.opsForValue().get(userEmailDto.getImageCodeKey());
        if (redisImageCode == null) {
            throw new BusinessException("验证码已过期，请重新获取！");
        }

        //4.校验图形验证码是否正确 - equalsIgnoreCase()忽略大小写比较
        if (!redisImageCode.toString().equalsIgnoreCase(userEmailDto.getImageCode())) {
            throw new BusinessException("图形验证码错误，请重新输入！");
        }

        //5.判断邮箱是否已经注册过
        User userEmail = userMapper.loadByEmail(userEmailDto.getEmail());
        if (userEmail != null) {
            throw new BusinessException("您已注册过，请返回登录界面直接登录！");
        }

        //6.保存logininof数据
        User user = userEmailDto2User(userEmailDto);
        Logininfo logininfo = user2Logininfo(user);

        //先保存logininof数据才能拿到Logininfo_id保存到user表中
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());

        //7.保存user数据
        userMapper.save(user);

    }

    /**
     * 将UserEmailDto对象的数据同步到User对象中
     * @param userEmailDto
     * @return
     */
    private User userEmailDto2User(UserEmailDto userEmailDto) {
        User user = new User();

        user.setUsername(userEmailDto.getEmail());
        user.setEmail(userEmailDto.getEmail());

        String salt = StrUtils.getComplexRandomString(32);
        user.setPassword(salt + userEmailDto.getPassword());
        user.setSalt(salt);

        return user;
    }


    /**
     * 将UserDto对象的数据同步到User对象中
     * @param userDto
     * @return
     */
    private User userDto2User(UserDto userDto) {
        //创建一个user对象
        User user = new User();

        /**
         * 将userDto现有的值赋值给user
         */
        //用户名就是手机号
        user.setUsername(userDto.getPhone());

        //手机号
        user.setPhone(userDto.getPhone());

        //密码 - 保存到数据库需要加盐加密
        //获取32位随机的盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //调用工具类加盐加密再保存到对象中
        user.setPassword(MD5Utils.encrypByMd5(salt + userDto.getPassword()));

        return user;
    }

    /**
     * 将user的值同步赋值给logininfo
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        //创建一个logininfo对象
        Logininfo logininfo = new Logininfo();
        //调用工具类：按照同名属性赋值 - 将user的值赋值给logininfo
        BeanUtils.copyProperties(user, logininfo);
        //设置type类型为1：表示用户
        logininfo.setType(1);

        return logininfo;
    }

    /**
     * 添加
     * @param user
     */
    @Override
    public void save(User user) {
        //员工密码添加到数据库需要加盐加密
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);

        //调用工具类加密密码
        String md5Pwd = MD5Utils.encrypByMd5(salt + user.getPassword());
        user.setPassword(md5Pwd);

        //同步
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        super.save(user);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Long id) {
        User user = userMapper.findOne(id);

        Long logininfoId = user.getLogininfoId();

        logininfoMapper.delete(logininfoId);


        super.delete(id);
    }


    /**
     * 修改
     * @param user
     */
    @Override
    public void update(User user) {
        //员工密码添加到数据库需要加盐加密
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);

        //调用工具类加密密码
        String md5Pwd = MD5Utils.encrypByMd5(salt + user.getPassword());
        user.setPassword(md5Pwd);

        //同步
        Logininfo logininfo = user2Logininfo(user);
        //通过user获取户信息id
        Long logininfoId = userMapper.findOne(user.getId()).getLogininfoId();
        logininfo.setId(logininfoId);

        logininfoMapper.update(logininfo);

        super.update(user);
    }
}
